package com.wei.chatroom.controller;

import com.wei.chatroom.model.User;
import com.wei.chatroom.model.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @projectName: chatroom
 * @package: com.wei.chatroom.controller
 * @className: UserController
 * @author: weiJiang
 * @description: 后端注册和登录接口
 * @date: 2025/9/18 下午2:24
 * @version: 1.0
 */

@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;

    /**
     * @author weiJiang
     * @description 去数据库看能不能找到对应的对象，登录成功就创建会话
     * @date 2025/9/18 下午2:30
     */
    @PostMapping("/login")
    public Object login(String username, String password, HttpServletRequest req){
        User user=userMapper.selectByName(username);

        if(user==null||!user.getPassword().equals(password)){
            //登录失败,返回信息和空对象
            System.out.println("用户名或密码不正确"+user);
            return new User();
        }
        //登录成功创建会话,true:会话不存在创建
        HttpSession session=req.getSession(true);
        session.setAttribute("user",user);//key和value
        //最好不要把密码返回到前端
        user.setPassword("");
        return user;
    }

    @PostMapping("/register")
    public Object register(String username, String password){
        //需要用useGeneratedKeys获取主键(在xml里面加)
        User user= null;
        try {
            user = new User();
            user.setUsername(username);
            user.setPassword(password);
            Integer ret=userMapper.insert(user);
            System.out.println("注册成功"+ret);
            user.setPassword("");//不要让密码返回到前端
        } catch (DuplicateKeyException e) {
            //名字重复，注册失败
            e.printStackTrace();
            user=new User();
        }

        return user;
    }

    /**
     * @param req: 需要通过会话获取或者保存用户信息
     * @return Object
     * @author weiJiang
     * @description 获取当前对话框中用户的信息
     * @date 2025/9/22 下午1:15
     */
    @GetMapping("/userInfo")
    public Object getUserInfo(HttpServletRequest req){
        //从请求中获取会话，并获取用户信息

        HttpSession session=req.getSession(false);
        if(session==null){
            System.out.println("会话不存在");
            //会话不存在(未登录),返回空对象
            return new User();

        }

        User user=(User) session.getAttribute("user");

        if(user==null){
            System.out.println("用户对象不存在");
            return new User();
        }
        user.setPassword("");
        return user;
    }
}
